/*
 * Thread_Mutex_Guard.h
 *
 *  Created on: 15/03/2011
 *      Author: Nikolaj
 */


#ifndef THREAD_MUTEX_GUARD_H_
#define THREAD_MUTEX_GUARD_H_

#include "../../os/OSAPI.h"

namespace os {
	class Thread_Mutex_Guard {
	public:
		inline Thread_Mutex_Guard(Mutex& lock) : lock_(&lock), owner_ (false) {
			lock_->signal();
			owner_ = true; // Only set to true if <acquire> succeeds.
		}

		inline ~Thread_Mutex_Guard () {
			// Only release the lock if it was acquired
			// successfully, i.e., <false> indicates that
			// <acquire> failed..
			if (owner_) {
				lock_->wait();
			}
		}

		private:
			Mutex* lock_;
			bool owner_;
			Thread_Mutex_Guard (const Thread_Mutex_Guard&);
			void operator= (const Thread_Mutex_Guard&);
		};
	}
#endif /* THREAD_MUTEX_GUARD_H_ */
